package com.example.easyexcel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.example.easyexcel.Service.UserService;
import com.example.easyexcel.entity.DemoData;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;

public class UploadListener implements ReadListener<DemoData> {

    private static Logger logger = LoggerFactory.getLogger(UploadListener.class);


    private UserService userService;

    private List<DemoData> cacheLists = new ArrayList<>(100);


    public UploadListener(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(DemoData data, AnalysisContext context) {
        logger.info("解析到一条数据: {}", JSON.toJSONString(data));
        cacheLists.add(data);
        if (cacheLists.size() > 100) {
            saveData();
            cacheLists = ListUtils.newArrayListWithExpectedSize(100);
        }
    }

    private void saveData() {
        logger.info("存储数据" + cacheLists.size() + "条!");
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        if (CollectionUtils.isNotEmpty(cacheLists)) {
            saveData();
            logger.info("所有数据解析完成！");
        }
    }

}
